import { store } from "@/store";
import { defineStore } from "pinia";
import SubjectApi, { type SubjectListParams, type SubjectType } from "@/api/merchant/subject";

export const useSubjectStore = defineStore("subject", () => {
  const list = ref<SubjectType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchSubjectList(params: SubjectListParams) {
    loading.list = true;
    const response = await SubjectApi.getSubjectList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreateSubject(subject: Partial<SubjectType>) {
    loading.create = true;
    try {
      await SubjectApi.addSubject(subject);
      loading.create = false;
    } catch (error) {
      console.error("Error creating subject:", error);
      loading.create = false;
    }
  }

  async function fetchUpdateSubject(subject: Partial<SubjectType>) {
    loading.update = true;
    try {
      await SubjectApi.updateSubject(subject);
      loading.update = false;
    } catch (error) {
      console.error("Error updating subject:", error);
      loading.update = false;
    }
  }

  async function fetchDeleteSubject(id: number) {
    loading.delete = true;
    await SubjectApi.deleteSubject(id);
    loading.delete = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchSubjectList,
    fetchCreateSubject,
    fetchUpdateSubject,
    fetchDeleteSubject,
  };
});

export const useSubjectStoreHook = () => {
  return useSubjectStore(store);
};
